const table = layui.table;
const laydate = layui.laydate;
const upload = layui.upload;
const form = layui.form;

form.verify( {
    username: function ( value, item ) {
        if ( value === "" ) {
            return "用户名不能为空";
        }
    }, password: [
        /^\S{6,12}$/, '密码必须6到12位，且不能出现空格'
    ]
} );

/**
 *
 * @param {string} password
 * @param {string} noise
 * @returns
 */
function calculateWords( password, noise ) {
    return hex_md5( hex_md5( password ) + noise );
}

form.on( 'submit(login-submit)', function ( data ) {
    console.log( data.field );

    let noise = '';

    $.ajax( {
        async: false, type: "GET", url: "/login/noise", success: function ( resp, status, xhr ) {
            console.log( resp );
            noise = resp;
        }, error: function ( xhr, status, error ) {
            console.log( error );
        }
    } );

    $.ajax( {
        type: "POST", url: "/login/post", data: JSON.stringify( {
            "username": data.field.username, "words": calculateWords( data.field.password, noise ), "noise": noise
        } ), contentType: "application/json; charset=utf-8", dataType: "text", success: function ( resp, status, xhr ) {
            if ( resp === 'ok' ) {
                layer.msg( resp, { time: 500 }, location.href = '/index' );
            } else {
                layer.alert( resp, { title: '登录失败' } );
            }
        }, error: function ( xhr, status, error ) {
            layer.alert( xhr.responseText, { title: '登录失败' } );
        }
    } );

    return false;
} );